package com.godenwater.recv.server.qx;

import cn.gov.mwr.sl651.utils.ByteUtil;
import com.godenwater.recv.RecvConstant;
import com.godenwater.recv.handler.AbstractHandler;
import com.godenwater.recv.model.CommonMessage;
import com.godenwater.recv.server.yf.YfDownCommand;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 西安山脉协议的处理器
 *
 * @author admin
 */
public class WeaterMessageHandler extends AbstractHandler {

    private static Logger logger = LoggerFactory
            .getLogger(WeaterMessageHandler.class);

    /**
     * Returns a singleton YfMessageHandler instance.
     *
     * @return a WeaterMessageHandler instance.
     */
    public static WeaterMessageHandler getInstance() {
        return WeaterMessageHandlerContainer.instance;
    }

    // Wrap this guy up so we can mock out the UserManager class.
    private static class WeaterMessageHandlerContainer {
        private static WeaterMessageHandler instance = new WeaterMessageHandler();
    }

    private WeaterMessageHandler() {
    }

    public void perform(String channel, IoSession session, CommonMessage message, int recvPort) {

        // 3、应答回复或重发报文请求
        byte[] replyMsg = null;

        // 确认应答
        logger.debug("收到【中国气象局】报文，发送\"应答\"回复....");
        replyMsg = YfDownCommand.reply();


        if (replyMsg != null
                && (channel.equalsIgnoreCase("GPRS") || channel
                .equalsIgnoreCase("UDP"))) {
            logger.debug("回复报文，" + ByteUtil.toHexString(replyMsg) + "");
            logger.info("S> " + ByteUtil.toHexString(replyMsg) + "");
            session.write(replyMsg);
        }

        // 6、前台监测通知
        String logMsg = new String(message.getContent());
        String stcd = logMsg.substring(1, 4);
        monitorMessage(channel, stcd, logMsg);

        // 7、 写入报文记录
        saveMessage(channel, RecvConstant.YF, stcd, true, logMsg, "0", "", "", 0, "", 0);
    }


    public boolean checkCRC(CommonMessage message) {
        return false;
    }

    public byte[] replyMessage(IoSession session, CommonMessage message) {
        return YfDownCommand.reply();
    }

    /**
     * @return
     */
    public byte[] repeatMessage(CommonMessage message) {
        return null;
    }


    public String viewMessage(CommonMessage message) {
        return new String(message.getContent());
    }


}
